<template>
  <div class="login-container">
    <!-- 头部 -->
    <van-nav-bar title="黑马头条" :fixed="true" />
    <!-- 登录表单 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="form.mobile"
        name="手机号码"
        label="手机号码"
        placeholder="手机号码"
        required
        :rules="[
          { required: true, message: '请填写手机号码' },
          { pattern: /^1\d{10}$/, message: '请填写正确的手机号' },
        ]"
      />
      <van-field
        v-model="form.code"
        type="password"
        name="登录`密码"
        label="登录密码"
        placeholder="登录密码"
        required
        :rules="[{ required: true, message: '请填写登录密码' }]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginApi } from '../../api/userApi'
import { mapMutations } from 'vuex'
export default {
  // 组件的name属性的值.首字母大写
  name: 'Login',
  data () {
    return {
      // 用户填写的
      form: {
        mobile: '15136865252',
        code: '246810'
      }
    }
  },
  methods: {
    ...mapMutations(['updateTokenInfo']),
    async onSubmit () {
      // 获取.调用
      // 封装调用接口
      // await只能被async修饰的方法内
      const { data: res } = await loginApi(this.form)
      console.log(res)
      if (res.message === 'OK') {
        // localStorage.setItem('token', JSON.stringify(res.data))
        this.updateTokenInfo(res.data)
        const navPath = this.$router.query.pre || '/'
        this.$router.push(navPath)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.login-container {
  padding-top: 46px;
}
</style>
